<template>
  <div class="vedit">
    <h1>{{ id ? "编辑" : "创建" }}视频信息</h1>

    <!-- model绑定表单模型 rules绑定表单验证规则 ref返回表单 -->
    <el-form
      label-position="top"
      :model="model"
      ref="ruleForm"
      @submit.native.prevent
    >
      <!-- prop 接受子组件 name值  validate-event绑定提交时验证-->
      <el-form-item prop="author" label="UP主">
        <el-input v-model="model.author" />
      </el-form-item>
      <el-form-item prop="title" label="标题">
        <el-input v-model="model.title" />
      </el-form-item>
      <el-form-item prop="type" label="分区">
        <el-select
          size="medium"
          v-model="model.type"
          filterable
          multiple
          placeholder="请选择分区"
        >
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="desc" label="描述">
        <el-input v-model="model.desc" />
      </el-form-item>
      <el-form-item prop="createdAt" label="上传时间">
        <span>{{ model.createdAt | fullDateFormat }}</span>
      </el-form-item>
      <el-form-item prop="imgUrl" label="封面地址">
        <el-input v-model="model.imgUrl" />
      </el-form-item>
      <el-form-item prop="videoUrl" label="视频地址">
        <el-input v-model="model.videoUrl" />
      </el-form-item>
      <el-form-item prop="playCount" label="播放量">
        <el-input v-model="model.playCount" />
      </el-form-item>
      <el-form-item prop="collectList" label="收藏数">
        <el-input v-model="model.collectList" />
      </el-form-item>
      <el-form-item prop="zanList" label="点赞数">
        <el-input v-model="model.zanList" />
      </el-form-item>
      <el-form-item prop="audit" label="审核状态">
        <el-switch
          v-model="model.audit"
          :active-text="model.audit ? '审核通过' : '未通过'"
        >
        </el-switch>
      </el-form-item>

      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <!-- 视频 -->
          <el-upload
            drag
            :auto-upload="false"
            :limit="1"
            name="video"
            action=""
            :on-change="videoUpload"
            :on-exceed="videoExceed"
            accept=".mp4,.flv"
            :on-remove="videoRemove"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将视频文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传mp4/flv文件，且不超过1GB
            </div>
          </el-upload>
        </el-col>
        <el-col :span="12" class="titlePic">
          <!-- 封面 -->
          <el-upload
            drag
            :auto-upload="false"
            :limit="1"
            name="img"
            class="avatar-uploader"
            action=""
            :on-change="imgUpload"
            :on-exceed="imgExceed"
            :on-remove="imgRemove"
            accept=".jpg,.jpeg,.png"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon">视频封面</i>
          </el-upload>
          <h4 class="el-upload__tip">只能上传jpg/jpeg/png文件，且不超过2MB</h4>
        </el-col>
      </el-row>
      <el-form-item>
        <!-- 提交时传入表单 -->
        <el-button
          type="primary"
          native-type="submit"
          @click="save('ruleForm')"
        >
          <span>保存</span>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { v1 } from "uuid"
export default {
  // 路由解耦，注入子组件参数
  props: {
    id: {},
  },
  data() {
    return {
      video: "",
      img: "",
      imgUrl: "",
      //分区数据
      categories: [],

      fileName: "",
      //默认隐藏弹窗
      dialogVisible: false,
      //数据模型model
      model: {},
      //上传文件名
      dataName: "",
    }
  },
  methods: {
    imgRemove() {
      this.imgUrl = ""
      this.img = ""
    },
    videoRemove() {
      this.video = ""
    },
    //文件个数超出回调
    videoExceed() {
      this.$message.error("视频只能上传一个")
    },
    imgExceed() {
      this.$message.error("图片只能上传一个")
    },
    videoUpload(file) {
      //存放视频数据
      this.video = file

      return true
    },
    imgUpload(file) {
      this.img = file
      return true
    },
    //确认上传

    //上传
    /*     afgerUpload(res) {
      this.model.headUrl = res.url
    }, */
    /*     beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!")
      }
      //文件名处理
      this.dataname.name = v1()
      return isLt2M
    }, */
    //保存或修改
    save(formName) {
      // validate 验证表单返回值
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let frm = new FormData()
          //加入数据
          frm.append("video", this.video.raw)
          frm.append("img", this.img.raw)

          //随机上传文件名
          this.dataName = v1()
          //加入文件名属性
          frm.append("name", this.dataName)
          //上传数据库
          let res = await this.$http.post("/upload", frm)
          this.model.videoUrl = res.data[0]
          this.model.imgUrl = res.data[1]
          if (res.data) {
            let res
            if (this.id) {
              //发送数据库修改put请求
              res = await this.$http.put("rest/videos", this.model)
            } else {
              //发送数据库创建post请求
              res = await this.$http.post("rest/videos", this.model)
            }
            console.log(res)
            // 判断是否已存在
            if (res.data.name != "MongoError") {
              //创建完成 跳转至列表
              this.$router.push("/videos/list")
              //创建消息提醒
              this.$notify({
                title: "成功",
                position: "top-left",
                type: "success",
                message: "视频信息保存成功！",
              })
            } else {
              this.$notify({
                title: "警告",
                position: "top-left",
                type: "warning",
                message: "视频已存在！",
              })
            }
          }
        }
      })
    },
    async fetch() {
      const res = await this.$http.get(`rest/videos/${this.id}`)
      this.model = res.data
    },
    //获取分区数据
    async fetchCategories() {
      const res = await this.$http.get(`rest/categories`)
      this.categories = res.data
    },
  },
  created() {
    this.fetchCategories()
    this.id && this.fetch()
  },
  beforeRouteLeave(to, from, next) {
    //离开时清空组件数据
    this.model = {}
    next()
  },
}
</script>
<style>
.vedit .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.vedit .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.vedit .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  line-height: 15rem;
}
.vedit .avatar {
  width: 32rem;
  height: 18rem;
  display: block;
}
</style>
